package tencent

import (
	"encoding/json"
	"log/slog"
	"net/url"
	"strconv"

	"gitee.com/gxcc/go-utils/utils"
)

type MapApi struct {
	Key string `json:"key"`
}

type AddressResult struct {
	Address            string             `json:"address"`
	FormattedAddresses FormattedAddresses `json:"formatted_addresses"`
	AddressComponent   AddressComponent   `json:"address_component"`
}

type AddressComponent struct {
	Nation       string `json:"nation"`
	Province     string `json:"province"`
	City         string `json:"city"`
	District     string `json:"district"`
	Street       string `json:"street"`
	StreetNumber string `json:"street_number"`
}

type FormattedAddresses struct {
	Recommend string `json:"recommend"`
	Rough     string `json:"rough"`
}

func NewTecentMapApi(key string) MapApi {
	return MapApi{
		Key: key,
	}
}

func (a MapApi) GeoCoder(gcjLat, gcjLng float64) (*AddressResult, error) {
	var reqValues = url.Values{}
	reqValues.Add("location", strconv.FormatFloat(gcjLat, 'f', 6, 64)+
		","+strconv.FormatFloat(gcjLng, 'f', 6, 64))
	reqValues.Add("get_poi", "0")
	reqValues.Add("key", a.Key)
	reqValues.Add("output", "JSON")

	var reqUrl = "https://apis.map.qq.com/ws/geocoder/v1/?" + reqValues.Encode()

	res, err := utils.HttpGet(reqUrl, nil)
	if err != nil {
		slog.Error(err.Error())
		return nil, err
	}

	type Result struct {
		Status    int           `json:"status"`
		Message   string        `json:"message"`
		RequestId string        `json:"request_id"`
		Result    AddressResult `json:"result"`
	}
	var result Result
	if err := json.Unmarshal(res.Body, &result); err != nil {
		slog.Error(err.Error())
		return nil, err
	}

	return &result.Result, nil
}
